package offerv1;

public class Offer47 {

    public int maxValue1(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0) {
            return 0;
        }

        int rows = grid.length, columns = grid[0].length;
        int[][] dict = new int[rows][columns];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                if (i == 0 && j == 0) {
                    dict[0][0] = grid[0][0];
                } else if (i == 0) {
                    dict[i][j] = dict[i][j - 1] + grid[i][j];
                } else if (j == 0) {
                    dict[i][j] = dict[i - 1][j] + grid[i][j];
                } else {
                    dict[i][j] = Math.max(dict[i - 1][j], dict[i][j - 1]) + grid[i][j];
                }
            }
        }

        return dict[rows - 1][columns - 1];
    }

    public int maxValue(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        for(int j = 1; j < n; j++) // 初始化第一行
            grid[0][j] += grid[0][j - 1];
        for(int i = 1; i < m; i++) // 初始化第一列
            grid[i][0] += grid[i - 1][0];
        for(int i = 1; i < m; i++)
            for(int j = 1; j < n; j++)
                grid[i][j] += Math.max(grid[i][j - 1], grid[i - 1][j]);
        return grid[m - 1][n - 1];
    }
}
